import { defineStore } from 'pinia'
import { RouteRecordRaw, RouterLink } from 'vue-router'
import { MenuOption } from 'naive-ui'
import { h } from 'vue'
import { getMenuInfo } from '@/api/base/base'
import { AppstoreTwotone as AppIcon } from '@vicons/antd'
import { Menu as MenuIcon } from '@vicons/carbon'
import { renderIcon } from '@/utils/common'
import router from '@/router'
import { ApiCode } from '@/enums/ApiCode'
import { useUserStore } from './user'
import { getCurrentRole } from '@/utils/cache'

export const useMenuStore = defineStore('menu', {
    state() {
        return {
            menuInfo: [] as Array<MenuInfo>
        }
    },
    getters: {
        menuRoutes(): Array<RouteRecordRaw>{
            return this.menuInfo.map(ele => {
                const children: Array<RouteRecordRaw> = ele.menus?.map(subEle => {
                    return {
                        name: subEle.name,
                        path: `${subEle.code}`,
                        component: () => import(`../../views/${ele.code}/${subEle.code}/Index.vue`)
                    }
                })
                return {
                    name: ele.name,
                    path: `/${ele.code}`,
                    component: () => import(`@/layout/Index.vue`),
                    children
                }
            })
        },
        menuOptions(): Array<MenuOption> {
            return this.menuInfo.map(ele => {
                const children = ele.menus?.map(subEle => {
                    return {
                        key: `/${ele.code}/${subEle.code}`,
                        label: () => h(
                            RouterLink, {
                                to: {path: `/${ele.code}/${subEle.code}`}
                            },
                            {default: () => subEle.name }
                        ),
                        icon: renderIcon(MenuIcon)
                    }
                })
                return {
                    key: `/${ele.code}`,
                    label: ele.name,
                    icon: renderIcon(AppIcon),
                    children
                }
            })
        }
    },
    actions: {
        async InitMenuInfo(): Promise<ApiResult<null>> {
            const currRoleId = getCurrentRole()
            const roleIds = useUserStore().userInfo.roles.map(ele => ele.id)
            const role = roleIds.includes(currRoleId) ? currRoleId : roleIds[0]
            const { data } = await getMenuInfo(role)

            this.menuInfo = data
            this.menuRoutes.forEach(ele => {
                router.addRoute(ele)
            })
            return {
                code: ApiCode.SUCCESS,
                message: '',
                data: null
            } 
        },
        destory(){
            this.menuInfo = []
        }
    }
})
